import { cloneDeep } from 'lodash-es'
/**
 * @description 格式化时间
 * @param time
 * @param cFormat
 * @returns {string|null}
 */
export function parseTime(time: string | number | Date, cFormat: string) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  return format.replace(/{([ymdhisa])+}/g, (result: string, key: string) => {
    let value = formatObj[key]
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = `0${value}`
    }
    return value || 0
  })
}
/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone<T>(source): T {
  return cloneDeep(source)
}
/**
 * @description 驼峰转-连接
 * @param str
 * @returns
 */
export function handler(str: string) {
  let tuo = ''
  const arr = str.split('')
  const newArr = arr.map((ite) => {
    return ite.toUpperCase() === ite ? (ite = '-' + ite.toLowerCase()) : ite
  })
  tuo = newArr.join('')
  return tuo
}
/**
 * @description 横线转驼峰
 * @param str
 * @returns str
 */
export function dashToCamelCase(str: string): string {
  return str.replace(/-(\w)/g, (match, p1) => p1.toUpperCase())
}

/**
 * @description 驼峰转横线
 * @param str
 * @returns str
 */
export function camelToDash(str: string): string {
  return str.replace(/([A-Z])/g, '-$1').toLowerCase()
}

/**
 * @description 一维数组转换为二维数组
 * @param data
 * @param rowLength
 * @returns array
 * @date 2024-01-30
 */
export function convertTo2DArray<T>(data: T[], rowLength: number): T[][] {
  const result: T[][] = []
  const dataLength = data.length

  for (let i = 0; i < dataLength; i += rowLength) {
    const row = data.slice(i, i + rowLength)
    result.push(row)
  }
  return result
}
